﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using System.Reflection;
using System.Text;
using Blackworks.Logger;
using Monocle.DataModel;

namespace Monocle.DataProvider
{
    public partial class SqlClient
    {
        /// <summary>
        /// Gets a pageitem by ID. 
        /// </summary>
        /// <param name="moduleID">The primary key of the module</param>
        /// <returns>The Facebook ModuleDTO</returns>
        public tFacebook GetFacebookModule(Guid moduleID)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            tFacebook queryResult = null;
            try
            {
                using (var context = new MonocleEntities(_connectionString))
                {
                    // Disable proxies for serialization purposes
                    context.ContextOptions.ProxyCreationEnabled = false;

                    queryResult = (from b in context.tFacebooks
                                   where b.PK_tFacebook == moduleID
                                   select b).SingleOrDefault();
                }
            }
            catch (Exception e)
            {
                Log.WriteExceptionLogEntry(String.Format("The webmethod {0} failed with Exception: " + Environment.NewLine + "{1}" + Environment.NewLine + "Stacktrace:" + Environment.NewLine + "{2}" + Environment.NewLine + "InnerException: {3}", MethodBase.GetCurrentMethod().Name, e.Message, e.StackTrace, e.InnerException == null ? String.Empty : e.InnerException.Message), LogEntryPriority.Critical);
            }
            finally
            {
                sw.Stop();
                Log.WritePerformanceLogEntry(String.Format("Web method {0} runtime in milliseconds: {1}", MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds), LogEntryPriority.Low);
            }

            if (queryResult == null)
                throw new ArgumentException("No match was found for the supplied primary key", "pageID");

            return queryResult;
        }

        /// <summary>
        /// Save a page to the database. Used for both updating and creating new entities
        /// </summary>
        /// <param name="dto">DTO to save</param>
        /// <returns>Saved DTO</returns>
        public tFacebook SaveFacebookModule(tFacebook dto)
        {
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            tFacebook returnValue = dto;
            if (dto == null)
                throw new ArgumentNullException("dto", "argument is not allowed to be null");

            try
            {
                using (var context = new MonocleEntities(_connectionString))
                {
                    if (dto.Version == null)
                    {
                        context.tFacebooks.AddObject(dto);
                    }
                    else
                    {
                        context.tFacebooks.Attach(dto);
                        context.ObjectStateManager.ChangeObjectState(dto, EntityState.Modified);
                    }

                    try
                    {
                        context.SaveChanges();
                    }
                    catch (OptimisticConcurrencyException)
                    {
                        // Resolve the concurrency conflict by refreshing the 
                        // object context before re-saving changes. 
                        context.Refresh(RefreshMode.ClientWins, dto);

                        // Save changes.
                        context.SaveChanges();
                    }
                    returnValue = dto;
                }
            }
            catch (Exception e)
            {
                Log.WriteExceptionLogEntry(String.Format("The webmethod {0} failed with Exception: " + Environment.NewLine + "{1}" + Environment.NewLine + "Stacktrace:" + Environment.NewLine + "{2}" + Environment.NewLine + "InnerException: {3}", MethodBase.GetCurrentMethod().Name, e.Message, e.StackTrace, e.InnerException == null ? String.Empty : e.InnerException.Message), LogEntryPriority.Critical);
                throw e;
            }
            finally
            {
                sw.Stop();
                Log.WritePerformanceLogEntry(String.Format("Web method {0} runtime in milliseconds: {1}", MethodBase.GetCurrentMethod().Name, sw.ElapsedMilliseconds), LogEntryPriority.Low);
            }
            return returnValue;
        }
    }
}
